#include <bits/stdc++.h>

using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode()
        : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x)
        : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right)
        : val(x), left(left), right(right) {}
};

class Solution {
   public:
    unordered_map<int, long long> m;
    void dfs(TreeNode* root, int level) {
        if (root == nullptr) {
            return;
        }
        m[level] += root->val;
        dfs(root->left, level + 1);
        dfs(root->right, level + 1);
    }
    long long kthLargestLevelSum(TreeNode* root, int k) {
        dfs(root, 0);
        if (m.size() < k) {
            return -1;
        }
        vector<long long> v;
        for (auto it = m.begin(); it != m.end(); ++it) {
            v.push_back(it->second);
        }
        sort(v.begin(), v.end(), greater<long long>());
        return v[k - 1];
    }
};